﻿using Microsoft.Extensions.DependencyInjection;
using PmSoft.Core;

namespace Demo.PetaPoco.Application.Services.Config;

/// <summary>
/// 通用配置服务抽象类，提供配置的获取和保存功能
/// </summary>
/// <typeparam name="TConfig">配置类型，必须是类且有无参构造函数</typeparam>
[Inject(ServiceLifetime.Scoped)]
public abstract class ConfigService<TConfig>(ConfigRepository repository) where TConfig : class, new()
{
    private readonly ConfigRepository _repository = repository ?? throw new ArgumentNullException(nameof(repository));

    protected virtual string ConfigKey { get => typeof(TConfig).Name; }

    /// <summary>
    /// 异步获取配置，若不存在则初始化并保存
    /// </summary>
    public async Task<TConfig> GetAsync()
    {
        var config = await _repository.GetAsync<TConfig>(ConfigKey);
        if (config != null)
        {
            return config;
        }

        config = new TConfig();
        await InitializeAsync(config);
        await _repository.SaveAsync(ConfigKey, config);
        return config;
    }
    /// <summary>
    /// 异步保存配置
    /// </summary>
    public async Task SaveAsync(TConfig config)
    {
        ArgumentNullException.ThrowIfNull(config);
        await _repository.SaveAsync(ConfigKey, config);
    }
    /// <summary>
    /// 初始化配置的抽象方法，由子类实现
    /// </summary>
    protected abstract Task InitializeAsync(TConfig config);

}